home *** CD-ROM | disk | FTP | other *** search
/ Languguage OS 2 / Languguage OS II Version 10-94 (Knowledge Media)(1994).ISO / gnu / bash_114.zip / bash-1.14.2 / shell.c < prev    next >
C/C++ Source or Header  |  1994-06-26  |  45KB  |  1,770 lines

  1. /* shell.c -- GNU's idea of the POSIX shell specification.
  2.  
  3.    This file is part of Bash, the Bourne Again SHell.  Bash is free
  4.    software; no one can prevent you from reading the source code, or
  5.    giving it to someone else.  This file is copyrighted under the GNU
  6.    General Public License, which can be found in the file called
  7.    COPYING.
  8.  
  9.    Copyright (C) 1988, 1991 Free Software Foundation, Inc.
  10.  
  11.    This file is part of GNU Bash.
  12.  
  13.    Bash is distributed in the hope that it will be useful, but WITHOUT
  14.    ANY WARRANTY.  No author or distributor accepts responsibility to
  15.    anyone for the consequences of using it or for whether it serves
  16.    any particular purpose or works at all, unless he says so in
  17.    writing.  Refer to the GNU Emacs General Public License for full
  18.    details.
  19.  
  20.    Everyone is granted permission to copy, modify and redistribute
  21.    Bash, but only under the conditions described in the GNU General
  22.    Public License.  A copy of this license is supposed to have been
  23.    given to you along with GNU Emacs so you can know your rights and
  24.    responsibilities.  It should be in a file named COPYING.
  25.  
  26.    Among other things, the copyright notice and this notice must be
  27.    preserved on all copies.
  28.  
  29.   Birthdate:
  30.   Sunday, January 10th, 1988.
  31.   Initial author: Brian Fox
  32. */
  33. #define INSTALL_DEBUG_MODE
  34.  
  35. #include "bashtypes.h"
  36. #include <stdio.h>
  37. #include <signal.h>
  38. #include <errno.h>
  39. #include <sys/file.h>
  40. #include "filecntl.h"
  41. #include <pwd.h>
  42. #include "posixstat.h"
  43. #include "bashansi.h"
  44.  
  45. #if defined (HAVE_VARARGS_H)
  46. #include <varargs.h>
  47. #endif
  48.  
  49. #include "shell.h"
  50. #include "flags.h"
  51.  
  52. #if defined (JOB_CONTROL)
  53. #include "jobs.h"
  54. #endif /* JOB_CONTROL */
  55.  
  56. #include "input.h"
  57. #include "execute_cmd.h"
  58.  
  59. #if defined (HISTORY)
  60. #  include "bashhist.h"
  61. #  include <readline/history.h>
  62. #endif
  63.  
  64. #include <tilde/tilde.h>
  65.  
  66. #if defined (USG) && !defined (HAVE_GETPW_DECLS)
  67. extern struct passwd *getpwuid ();
  68. #endif /* USG && !HAVE_GETPW_DECLS */
  69.  
  70. extern int yydebug;
  71. #if !defined (errno)
  72. extern int errno;
  73. #endif
  74.  
  75. extern char *dist_version;
  76. extern int patch_level, build_version;
  77. extern int subshell_environment; /* Found in execute_cmd.c. */
  78. extern int last_command_exit_value;
  79. extern int return_catch_flag;
  80. extern jmp_buf return_catch;
  81. extern int need_here_doc, current_command_line_count, line_number;
  82. extern char *ps1_prompt, **prompt_string_pointer;
  83. extern int loop_level, continuing, breaking;
  84. extern int parse_and_execute_level;
  85. extern char *this_command_name;
  86.  
  87. /* Non-zero means that this shell has already been run; i.e. you should
  88.    call shell_reinitialize () if you need to start afresh. */
  89. static int shell_initialized = 0;
  90. static int sourced_env = 0;
  91.  
  92. /* The current maintainer of the shell.  You change this in the
  93.    Makefile. */
  94. #if !defined (MAINTAINER)
  95. #define MAINTAINER "deliberately-anonymous"
  96. #endif
  97.  
  98. char *the_current_maintainer = MAINTAINER;
  99.  
  100. char *primary_prompt = PPROMPT;
  101. char *secondary_prompt = SPROMPT;
  102.  
  103. COMMAND *global_command = (COMMAND *)NULL;
  104.  
  105. /* Non-zero after SIGINT. */
  106. int interrupt_state = 0;
  107.  
  108. /* Information about the current user. */
  109. struct user_info current_user =
  110. {
  111.   -1, -1, -1, -1, (char *)NULL, (char *)NULL, (char *)NULL
  112. };
  113.  
  114. /* The current host's name. */
  115. char *current_host_name = (char *)NULL;
  116.  
  117. /* Non-zero means that this shell is a login shell.
  118.    Specifically:
  119.    0 = not login shell.
  120.    1 = login shell from getty (or equivalent fake out)
  121.   -1 = login shell from "-login" flag.
  122.   -2 = both from getty, and from flag.
  123.  */
  124. int login_shell = 0;
  125.  
  126. /* Non-zero means that at this moment, the shell is interactive.  In
  127.    general, this means that the shell is at this moment reading input
  128.    from the keyboard. */
  129. int interactive = 0;
  130.  
  131. /* Non-zero means that the shell was started as an interactive shell. */
  132. int interactive_shell = 0;
  133.  
  134. /* Tells what state the shell was in when it started:
  135.     0 = non-interactive shell script
  136.     1 = interactive
  137.     2 = -c command
  138.    This is a superset of the information provided by interactive_shell.
  139. */
  140. int startup_state = 0;
  141.  
  142. /* Special debugging helper. */
  143. int debugging_login_shell = 0;
  144.  
  145. /* The environment that the shell passes to other commands. */
  146. char **shell_environment;
  147.  
  148. /* Non-zero when we are executing a top-level command. */
  149. int executing = 0;
  150.  
  151. /* The number of commands executed so far. */
  152. int current_command_number = 1;
  153.  
  154. /* The environment at the top-level REP loop.  We use this in the case of
  155.    error return. */
  156. jmp_buf top_level, catch;
  157.  
  158. #if defined (JOB_CONTROL) || defined (_POSIX_VERSION)
  159. /* The signal masks that this shell runs with. */
  160. sigset_t top_level_mask;
  161. #endif /* JOB_CONTROL */
  162.  
  163. /* Non-zero is the recursion depth for commands. */
  164. int indirection_level = 0;
  165.  
  166. /* The number of times BASH has been executed.  This is set
  167.    by initialize_variables () in variables.c. */
  168. int shell_level = 0;
  169.  
  170. /* The name of this shell, as taken from argv[0]. */
  171. char *shell_name = (char *)NULL;
  172.  
  173. /* time in seconds when the shell was started */
  174. time_t shell_start_time;
  175.  
  176. /* The name of the .(shell)rc file. */
  177. static char *bashrc_file = "~/.bashrc";
  178.  
  179. /* Non-zero means to act more like the Bourne shell on startup. */
  180. static int act_like_sh = 0;
  181.  
  182. /* Values for the long-winded argument names. */
  183. static int debugging = 0;        /* Do debugging things. */
  184. static int no_rc = 0;            /* Don't execute ~/.bashrc */
  185. static int no_profile = 0;        /* Don't execute .profile */
  186. static int do_version = 0;        /* Display interesting version info. */
  187. static int quiet = 0;            /* Be quiet when starting up. */
  188. static int make_login_shell = 0;    /* Make this shell be a `-bash' shell. */
  189.  
  190. int no_line_editing = 0;    /* Don't do fancy line editing. */
  191. int no_brace_expansion = 0;    /* Non-zero means no foo{a,b} -> fooa foob. */
  192.  
  193. int posixly_correct = 0;    /* Non-zero means posix.2 superset. */
  194.  
  195. /* Some long-winded argument names.  These are obviously new. */
  196. #define Int 1
  197. #define Charp 2
  198. struct {
  199.   char *name;
  200.   int type;
  201.   int *int_value;
  202.   char **char_value;
  203. } long_args[] = {
  204.   { "debug", Int, &debugging, (char **)0x0 },
  205.   { "norc", Int, &no_rc, (char **)0x0 },
  206.   { "noprofile", Int, &no_profile, (char **)0x0 },
  207.   { "rcfile", Charp, (int *)0x0, &bashrc_file },
  208.   { "version", Int, &do_version, (char **)0x0 },
  209.   { "quiet", Int, &quiet, (char **)0x0 },
  210.   { "login", Int, &make_login_shell, (char **)0x0 },
  211.   { "nolineediting", Int, &no_line_editing, (char **)0x0 },
  212.   { "nobraceexpansion", Int, &no_brace_expansion, (char **)0x0 },
  213.   { "posix", Int, &posixly_correct, (char **)0x0 },
  214.   { (char *)0x0, Int, (int *)0x0, (char **)0x0 }
  215. };
  216.  
  217. /* These are extern so execute_simple_command can set them, and then
  218.    longjmp back to main to execute a shell script, instead of calling
  219.    main () again and resulting in indefinite, possibly fatal, stack
  220.    growth. */
  221. jmp_buf subshell_top_level;
  222. int subshell_argc;
  223. char **subshell_argv;
  224. char **subshell_envp;
  225.  
  226. #if defined (BUFFERED_INPUT)
  227. /* The file descriptor from which the shell is reading input. */
  228. int default_buffered_input = -1;
  229. #endif
  230.  
  231. static int want_pending_command;
  232. static char *local_pending_command;
  233.  
  234. static int isnetconn ();
  235. static void run_startup_files ();
  236.  
  237. static void shell_initialize ();
  238. static void shell_reinitialize ();
  239. static void initialize_signals ();
  240. static void initialize_terminating_signals ();
  241.  
  242. main (argc, argv, env)
  243.      int argc;
  244.      char **argv, **env;
  245. {
  246.   register int i;
  247.   int arg_index, locally_skip_execution;
  248.   int top_level_arg_index, read_from_stdin;
  249.   FILE *default_input;
  250.  
  251.   /* There is a bug in the NeXT 2.1 rlogind that causes opens
  252.      of /dev/tty to fail. */
  253. #if defined (RLOGIN_PGRP_BUG)
  254.   {
  255.     int tty_fd;
  256.  
  257.     tty_fd = open ("/dev/tty", O_RDWR);
  258.  
  259.     if (tty_fd < 0)
  260.       {
  261.     char *tty;
  262.     tty = (char *)ttyname (fileno (stdin));
  263.     tty_fd = open (tty, O_RDWR);
  264.       }
  265.     close (tty_fd);
  266.   }
  267. #endif /* RLOGIN_PGRP_BUG */
  268.  
  269.   /* Wait forever if we are debugging a login shell. */
  270.   while (debugging_login_shell);
  271.  
  272.   current_user.uid = getuid ();
  273.   current_user.gid = getgid ();
  274.   current_user.euid = geteuid ();
  275.   current_user.egid = getegid ();
  276.  
  277.   /* See whether or not we are running setuid or setgid. */
  278.   privileged_mode = (current_user.uid != current_user.euid) ||
  279.             (current_user.gid != current_user.egid);
  280.  
  281.   posixly_correct = (getenv ("POSIXLY_CORRECT") != (char *)NULL) ||
  282.             (getenv ("POSIX_PEDANTIC") != (char *)NULL);
  283.  
  284. #if defined (USE_GNU_MALLOC_LIBRARY)
  285.   mcheck (programming_error, (void (*) ())0);
  286. #endif /* USE_GNU_MALLOC_LIBRARY */
  287.  
  288.   if (setjmp (subshell_top_level))
  289.     {
  290.       argc = subshell_argc;
  291.       argv = subshell_argv;
  292.       env = subshell_envp;
  293.       sourced_env = 0;
  294.     }
  295.  
  296.   /* Initialize local variables for all `invocations' of main (). */
  297.   arg_index = 1;
  298.   local_pending_command = (char *)NULL;
  299.   want_pending_command = 0;
  300.   locally_skip_execution = 0;
  301.   read_from_stdin = 0;
  302.   default_input = stdin;
  303. #if defined (BUFFERED_INPUT)
  304.   default_buffered_input = -1;
  305. #endif
  306.  
  307.   /* Fix for the `infinite process creation' bug when running shell scripts
  308.      from startup files on System V. */
  309.   login_shell = make_login_shell = 0;
  310.  
  311.   /* If this shell has already been run, then reinitialize it to a
  312.      vanilla state. */
  313.   if (shell_initialized || shell_name)
  314.     {
  315.       /* Make sure that we do not infinitely recurse as a login shell. */
  316.       if (*shell_name == '-')
  317.     shell_name++;
  318.  
  319.       shell_reinitialize ();
  320.       if (setjmp (top_level))
  321.     exit (2);
  322.     }
  323.  
  324.   /* Here's a hack.  If the name of this shell is "sh", then don't do
  325.      any startup files; just try to be more like /bin/sh. */
  326.   /* XXX - next version - make this be the same as -posix. */
  327.   shell_name = base_pathname (argv[0]);
  328.   if (*shell_name == '-')
  329.     shell_name++;
  330.   if (shell_name[0] == 's' && shell_name[1] == 'h' && !shell_name[2])
  331.     act_like_sh++;
  332.  
  333.   yydebug = 0;
  334.  
  335.   shell_environment = env;
  336.   shell_name = argv[0];
  337.   dollar_vars[0] = savestring (shell_name);
  338.  
  339.   if (*shell_name == '-')
  340.     {
  341.       shell_name++;
  342.       login_shell++;
  343.     }
  344.  
  345. #if defined (JOB_CONTROL)
  346.   if (act_like_sh)
  347.     job_control = 0;        /* XXX - not posix */
  348. #endif /* JOB_CONTROL */
  349.  
  350.   shell_start_time = NOW;    /* NOW now defined in general.h */
  351.  
  352.   /* A program may start an interactive shell with
  353.       "execl ("/bin/bash", "-", NULL)".
  354.      If so, default the name of this shell to our name. */
  355.   if (!shell_name || !*shell_name || (shell_name[0] == '-' && !shell_name[1]))
  356.     shell_name = "bash";
  357.  
  358.   /* Parse argument flags from the input line. */
  359.  
  360.   /* Find full word arguments first. */
  361.   while ((arg_index != argc) && *(argv[arg_index]) == '-')
  362.     {
  363.       for (i = 0; long_args[i].name; i++)
  364.     {
  365.       if (STREQ (&(argv[arg_index][1]), long_args[i].name))
  366.         {
  367.           if (long_args[i].type == Int)
  368.         *long_args[i].int_value = 1;
  369.           else
  370.         {
  371.           if (!argv[++arg_index])
  372.             {
  373.               report_error ("option `%s' expected an argument",
  374.                     long_args[i].name);
  375.               exit (1);
  376.             }
  377.           else
  378.             *long_args[i].char_value = argv[arg_index];
  379.         }
  380.           goto handle_next_arg;
  381.         }
  382.     }
  383.       break;            /* No such argument.  Maybe flag arg. */
  384.     handle_next_arg:
  385.       arg_index++;
  386.     }
  387.  
  388.   /* If we're in a strict Posix.2 mode, turn on interactive comments. */
  389.   if (posixly_correct)
  390.     interactive_comments = 1;
  391.  
  392.   /* If user supplied the "-login" flag, then set and invert LOGIN_SHELL. */
  393.   if (make_login_shell)
  394.     {
  395.       login_shell++;
  396.       login_shell = -login_shell;
  397.     }
  398.  
  399.   /* All done with full word options; do standard shell option parsing.*/
  400.   this_command_name = shell_name;    /* for error reporting */
  401.   while (arg_index != argc && argv[arg_index] &&
  402.      (*argv[arg_index] == '-' || *argv[arg_index] == '+'))
  403.     {
  404.       /* There are flag arguments, so parse them. */
  405.       int arg_character, on_or_off, next_arg;
  406.       char *o_option, *arg_string;
  407.  
  408.       i = 1;
  409.       next_arg = arg_index + 1;
  410.       arg_string = argv[arg_index];
  411.       on_or_off = arg_string[0];
  412.  
  413.       /* A single `-' signals the end of options.  From the 4.3 BSD sh.
  414.      An option `--' means the same thing; this is the standard
  415.      getopt(3) meaning. */
  416.       if (arg_string[0] == '-' &&
  417.        (arg_string[1] == '\0' ||
  418.          (arg_string[1] == '-' && arg_string[2] == '\0')))
  419.     {
  420.       arg_index++;
  421.       break;
  422.     }
  423.  
  424.       while (arg_character = arg_string[i++])
  425.     {
  426.       switch (arg_character)
  427.         {
  428.         case 'c':
  429.         want_pending_command = 1;
  430.         break;
  431.  
  432.         case 's':
  433.         read_from_stdin = 1;
  434.         break;
  435.  
  436.         case 'o':
  437.         o_option = argv[next_arg];
  438.         if (!o_option)
  439.           {
  440.             list_minus_o_opts ();
  441.             break;
  442.           }
  443.         if (set_minus_o_option (on_or_off, o_option) != EXECUTION_SUCCESS)
  444.           exit (1);
  445.         next_arg++;
  446.         break;
  447.  
  448.         default:
  449.           if (change_flag (arg_character, on_or_off) == FLAG_ERROR)
  450.         {
  451.           report_error ("%c%c: bad option", on_or_off, arg_character);
  452.           exit (1);
  453.         }
  454.  
  455.         }
  456.     }
  457.       /* Can't do just a simple increment anymore -- what about
  458.      "bash -abouo emacs ignoreeof -hP"? */
  459.       arg_index = next_arg;
  460.     }
  461.  
  462.   /* Need to get the argument to a -c option processed in the
  463.      above loop.  The next arg is a command to execute, and the
  464.      following args are $0...$n respectively. */
  465.   if (want_pending_command)
  466.     {
  467.       local_pending_command = argv[arg_index];
  468.       if (!local_pending_command)
  469.     {
  470.       report_error ("`-c' requires an argument");
  471.       exit (1);
  472.     }
  473.       arg_index++;
  474.     }
  475.   this_command_name = (char *)NULL;      
  476.  
  477.   /* First, let the outside world know about our interactive status.
  478.      A shell is interactive if the `-i' flag was given, or if all of
  479.      the following conditions are met:
  480.     no -c command
  481.     no arguments remaining or the -s flag given
  482.     standard input is a terminal
  483.     standard output is a terminal
  484.      Refer to Posix.2, the description of the `sh' utility. */
  485.  
  486.   if (forced_interactive ||        /* -i flag */
  487.       (!local_pending_command &&    /* No -c command and ... */
  488.        ((arg_index == argc) ||        /*   no remaining args or... */
  489.     read_from_stdin) &&        /*   -s flag with args, and */
  490.        isatty (fileno (stdin)) &&    /* Input is a terminal and */
  491.        isatty (fileno (stdout))))    /* output is a terminal. */
  492.     {
  493.       interactive_shell = startup_state = interactive = 1;
  494.     }
  495.   else
  496.     {
  497. #if defined (HISTORY)
  498.       history_expansion = remember_on_history = 0;
  499. #endif /* HISTORY */
  500.       interactive_shell = startup_state = interactive = 0;
  501.       no_line_editing = 1;
  502. #if defined (JOB_CONTROL)
  503.       job_control = 0;
  504. #endif /* JOB_CONTROL */
  505.     }
  506.  
  507. #define CLOSE_FDS_AT_LOGIN
  508. #if defined (CLOSE_FDS_AT_LOGIN)
  509.   /*
  510.    * Some systems have the bad habit of starting login shells with lots of open
  511.    * file descriptors.  For instance, most systems that have picked up the
  512.    * pre-4.0 Sun YP code leave a file descriptor open each time you call one
  513.    * of the getpw* functions, and it's set to be open across execs.  That
  514.    * means one for login, one for xterm, one for shelltool, etc.
  515.    */
  516.   if (login_shell && interactive_shell)
  517.     {
  518.       for (i = 3; i < 20; i++)
  519.     close (i);
  520.     }
  521. #endif /* CLOSE_FDS_AT_LOGIN */
  522.  
  523.   /* From here on in, the shell must be a normal functioning shell.
  524.      Variables from the environment are expected to be set, etc. */
  525.   shell_initialize ();
  526.  
  527.   if (interactive_shell)
  528.     {
  529.       char *term = getenv ("TERM");
  530.       no_line_editing |= term && (STREQ (term, "emacs"));
  531.     }
  532.  
  533.   top_level_arg_index = arg_index;
  534.  
  535.   if (!quiet && do_version)
  536.     show_shell_version ();
  537.  
  538.   /* Give this shell a place to longjmp to before executing the
  539.      startup files.  This allows users to press C-c to abort the
  540.      lengthy startup. */
  541.   {
  542.     int code;
  543.  
  544.     code = setjmp (top_level);
  545.  
  546.     if (code)
  547.       {
  548.     if (code == EXITPROG)
  549.       goto exit_shell;
  550.     else
  551.       locally_skip_execution++;
  552.       }
  553.   }
  554.  
  555.   arg_index = top_level_arg_index;
  556.  
  557.   /* Execute the start-up scripts. */
  558.  
  559.   if (!interactive_shell)
  560.     {
  561.       makunbound ("PS1", shell_variables);
  562.       makunbound ("PS2", shell_variables);
  563.       interactive = 0;
  564.     }
  565.   else
  566.     {
  567.       change_flag ('i', FLAG_ON);
  568.       interactive = 1;
  569.     }
  570.  
  571.   if (!locally_skip_execution)
  572.     run_startup_files ();
  573.  
  574. #if defined (RESTRICTED_SHELL)
  575.       /* I turn on the restrictions afterwards because it is explictly
  576.      stated in the POSIX spec that PATH cannot be set in a restricted
  577.      shell, except in .profile. */
  578.     maybe_make_restricted (shell_name);
  579. #endif /* RESTRICTED_SHELL */
  580.  
  581.     if (local_pending_command)
  582.       {
  583.     /* Bind remaining args to $0 ... $n */
  584.     WORD_LIST *args = (WORD_LIST *)NULL;
  585.     while (arg_index != argc)
  586.       args = make_word_list (make_word (argv[arg_index++]), args);
  587.     if (args)
  588.       {
  589.         args = REVERSE_LIST (args, WORD_LIST *);
  590.         /* Posix.2 4.56.3 says that the first argument after
  591.            sh -c command becomes $0, and the rest of the arguments
  592.            are bound to $1 ... $N. */
  593.         shell_name = savestring (args->word->word);    /* XXX */
  594.         dollar_vars[0] = savestring (args->word->word);
  595.         remember_args (args->next, 1);
  596.         dispose_words (args);
  597.       }
  598.  
  599.     startup_state = 2;
  600. #if defined (ONESHOT)
  601.     run_one_command (local_pending_command);
  602.     goto exit_shell;
  603. #else /* ONESHOT */
  604.     with_input_from_string (local_pending_command, "-c");
  605.     goto read_and_execute;
  606. #endif /* !ONESHOT */
  607.       }
  608.  
  609.   /* Do the things that should be done only for interactive shells. */
  610.   if (interactive_shell)
  611.     {
  612.       /* Set up for checking for presence of mail. */
  613.       remember_mail_dates ();
  614.       reset_mail_timer ();
  615.  
  616. #if defined (HISTORY)
  617.       /* Initialize the interactive history stuff. */
  618.       if (!shell_initialized)
  619.     load_history ();
  620. #endif /* HISTORY */
  621.  
  622.       /* Initialize terminal state for interactive shells after the
  623.      .bash_profile and .bashrc are interpreted. */
  624.       get_tty_state ();
  625.     }
  626.  
  627.   /* Get possible input filename. */
  628.   if ((arg_index != argc) && !read_from_stdin)
  629.     {
  630.       int fd;
  631.       char *filename;
  632.  
  633.       free (dollar_vars[0]);
  634.       dollar_vars[0] = savestring (argv[arg_index]);
  635.       filename = savestring (argv[arg_index]);
  636.  
  637.       fd = open (filename, O_RDONLY);
  638.       if ((fd < 0) && (errno == ENOENT) && (absolute_program (filename) == 0))
  639.     {
  640.       char *path_filename;
  641.       /* If it's not in the current directory, try looking through PATH
  642.          for it. */
  643.       path_filename = find_path_file (argv[arg_index]);
  644.       if (path_filename)
  645.         {
  646.           free (filename);
  647.           filename = path_filename;
  648.           fd = open (filename, O_RDONLY);
  649.         }
  650.     }
  651.  
  652.       arg_index++;
  653.       if (fd < 0)
  654.     {
  655.       file_error (filename);
  656.       exit (1);
  657.     }
  658.  
  659.       /* Only do this with file descriptors we can seek on. */
  660.       if (lseek (fd, 0L, 1) != -1)
  661.     {
  662.       unsigned char sample[80];
  663.       int sample_len;
  664.  
  665.       /* Check to see if the `file' in `bash file' is a binary file
  666.          according to the same tests done by execute_simple_command (),
  667.          and report an error and exit if it is. */
  668.       sample_len = read (fd, sample, sizeof (sample));
  669.       if (sample_len > 0 && (check_binary_file (sample, sample_len)))
  670.         {
  671.           report_error ("%s: cannot execute binary file", filename);
  672.           exit (EX_BINARY_FILE);
  673.         }
  674.       /* Now rewind the file back to the beginning. */
  675.       lseek (fd, 0L, 0);
  676.     }
  677.  
  678. #if defined (BUFFERED_INPUT)
  679.       default_buffered_input = fd;
  680.       if (default_buffered_input == -1)
  681.     {
  682.       file_error (filename);
  683.       exit (127);
  684.     }
  685.       SET_CLOSE_ON_EXEC (default_buffered_input);
  686.  
  687. #else /* !BUFFERED_INPUT */
  688.  
  689.       /* Open the script.  But try to move the file descriptor to a randomly
  690.      large one, in the hopes that any descriptors used by the script will
  691.      not match with ours. */
  692.       {
  693.     int script_fd, nfds;
  694.  
  695.     nfds = getdtablesize ();
  696.     if (nfds <= 0)
  697.       nfds = 20;
  698.     if (nfds > 256)
  699.       nfds = 256;
  700.     script_fd = dup2 (fd, nfds - 1);
  701.     if (script_fd)
  702.       {
  703.         close (fd);
  704.         fd = script_fd;
  705.       }
  706.       }
  707.  
  708.       default_input = fdopen (fd, "r");
  709.  
  710.       if (!default_input)
  711.     {
  712.       file_error (filename);
  713.       exit (127);
  714.     }
  715.  
  716.       SET_CLOSE_ON_EXEC (fd);
  717.       if (fileno (default_input) != fd)
  718.     SET_CLOSE_ON_EXEC (fileno (default_input));
  719.  
  720. #endif /* !BUFFERED_INPUT */
  721.  
  722.       if (!interactive_shell || (!isatty (fd)))
  723.     {
  724. #if defined (HISTORY)
  725.       history_expansion = 0;
  726.       remember_on_history = 0;
  727. #endif /* HISTORY */
  728.       interactive = interactive_shell = 0;
  729.       no_line_editing = 1;
  730. #if defined (JOB_CONTROL)
  731.       set_job_control (0);
  732. #endif /* JOB_CONTROL */
  733.     }
  734.       else
  735.     {
  736.       /* I don't believe that this code is ever executed, even in
  737.          the presence of /dev/fd. */
  738.       dup2 (fd, 0);
  739.       close (fd);
  740.       fclose (default_input);
  741.     }
  742.     }
  743.   else if (!interactive)
  744.     /* In this mode, bash is reading a script from stdin, which is a
  745.        pipe or redirected file. */
  746. #if defined (BUFFERED_INPUT)
  747.     default_buffered_input = fileno (stdin);    /* == 0 */
  748. #else      
  749.     setbuf (default_input, (char *)NULL);
  750. #endif /* !BUFFERED_INPUT */
  751.  
  752.   /* Bind remaining args to $1 ... $n */
  753.   {
  754.     WORD_LIST *args = (WORD_LIST *)NULL;
  755.     while (arg_index != argc)
  756.       args = make_word_list (make_word (argv[arg_index++]), args);
  757.     args = REVERSE_LIST (args, WORD_LIST *);
  758.     remember_args (args, 1);
  759.     dispose_words (args);
  760.   }
  761.  
  762. #if defined (BUFFERED_INPUT)
  763.   if (!interactive)
  764.     unset_nodelay_mode (default_buffered_input);
  765.   else
  766.     unset_nodelay_mode (fileno (stdin));
  767. #else
  768.   unset_nodelay_mode (fileno (stdin));
  769. #endif /* !BUFFERED_INPUT */
  770.  
  771.   /* with_input_from_stdin really means `with_input_from_readline' */
  772.   if (interactive && !no_line_editing)
  773.     with_input_from_stdin ();
  774.   else
  775. #if defined (BUFFERED_INPUT)
  776.     {
  777.       if (!interactive)
  778.     with_input_from_buffered_stream (default_buffered_input, dollar_vars[0]);
  779.       else
  780.     with_input_from_stream (default_input, dollar_vars[0]);
  781.     }
  782. #else /* !BUFFERED_INPUT */
  783.     with_input_from_stream (default_input, dollar_vars[0]);
  784. #endif /* !BUFFERED_INPUT */
  785.  
  786. #if !defined (ONESHOT)
  787.  read_and_execute:
  788. #endif /* !ONESHOT */
  789.  
  790.   shell_initialized = 1;
  791.  
  792.   /* Read commands until exit condition. */
  793.   reader_loop ();
  794.  
  795.   exit_shell:
  796.   /* Do trap[0] if defined. */
  797.   run_exit_trap ();
  798.  
  799. #if defined (PROCESS_SUBSTITUTION)
  800.   unlink_fifo_list ();
  801. #endif /* PROCESS_SUBSTITUTION */
  802.  
  803. #if defined (HISTORY)
  804.   if (interactive && remember_on_history)
  805.     maybe_save_shell_history ();
  806. #endif /* HISTORY */
  807.  
  808. #if defined (JOB_CONTROL)
  809.   /* If this shell is interactive, terminate all stopped jobs and
  810.      restore the original terminal process group. */
  811.   end_job_control ();
  812. #endif /* JOB_CONTROL */
  813.  
  814.   /* Always return the exit status of the last command to our parent. */
  815.   exit (last_command_exit_value);
  816. }
  817.  
  818. #if !defined (SYS_PROFILE)
  819. #  define SYS_PROFILE "/etc/profile"
  820. #endif /* !SYS_PROFILE */
  821.  
  822. /* Source the bash startup files.  If POSIXLY_CORRECT is non-zero, we obey
  823.    the Posix.2 startup file rules:  $ENV is expanded, and if the file it
  824.    names exists, that file is sourced.  The Posix.2 rules are in effect
  825.    for both interactive and non-interactive shells (section 4.56.5.3) */
  826. static void
  827. run_startup_files ()
  828. {
  829.   if (!posixly_correct)
  830.     {
  831.       if (login_shell)
  832.     {
  833.       /* We don't execute .bashrc for login shells. */
  834.           no_rc++;
  835.           maybe_execute_file (SYS_PROFILE, 1);
  836.         }
  837.  
  838.       if (login_shell && !no_profile)
  839.         {
  840.           if (act_like_sh)
  841.             maybe_execute_file ("~/.profile", 1);
  842.           else
  843.             {
  844.               if (maybe_execute_file ("~/.bash_profile", 1) == 0)
  845.             if (maybe_execute_file ("~/.bash_login", 1) == 0)
  846.               maybe_execute_file ("~/.profile", 1);
  847.             }
  848.         }
  849.  
  850.       /* Execute ~/.bashrc for most shells.  Never execute it if
  851.          ACT_LIKE_SH is set, or if NO_RC is set.
  852.  
  853.          If the executable file "/usr/gnu/src/bash/foo" contains:
  854.  
  855.            #!/usr/gnu/bin/bash
  856.            echo hello
  857.  
  858.          then:
  859.  
  860.          COMMAND        EXECUTE BASHRC
  861.          --------------------------------
  862.          bash -c foo        NO
  863.          bash foo        NO
  864.          foo            NO
  865.          rsh machine ls        YES (for rsh, which calls `bash -c')
  866.          rsh machine foo    YES (for shell started by rsh) NO (for foo!)
  867.          echo ls | bash        NO
  868.          login            NO
  869.          bash            YES
  870.       */
  871.       if (!act_like_sh && !no_rc &&
  872.           (interactive_shell || (isnetconn (fileno (stdin)) &&
  873.                      local_pending_command)))
  874.         maybe_execute_file (bashrc_file, 1);
  875.     }
  876.  
  877.    /* Try a TMB suggestion.  If running a script, then execute the
  878.       file mentioned in the ENV variable. */
  879.    if (!privileged_mode && sourced_env++ == 0 &&
  880.        (posixly_correct || !interactive_shell))
  881.     {
  882.       char *env_file = (char *)NULL;
  883.  
  884.       if (!posixly_correct)
  885.     env_file = getenv ("BASH_ENV");
  886.       if (!env_file)
  887.     env_file = getenv ("ENV");
  888.  
  889.       if (env_file && *env_file)
  890.     {
  891.       WORD_LIST *list;
  892.       char *expanded_file_name;
  893.  
  894.       list = expand_string_unsplit (env_file, 1);
  895.       if (list)
  896.         {
  897.           expanded_file_name = string_list (list);
  898.           dispose_words (list);
  899.  
  900.           if (expanded_file_name && *expanded_file_name)
  901.         maybe_execute_file (expanded_file_name, 1);
  902.  
  903.           if (expanded_file_name)
  904.         free (expanded_file_name);
  905.         }
  906.     }
  907.     }
  908. }
  909.  
  910. #if defined (RESTRICTED_SHELL)
  911. /* Perhaps make this shell a `restricted' one, based on NAME.
  912.    If the basename of NAME is "rbash", then this shell is restricted.
  913.    In a restricted shell, PATH and SHELL are read-only and non-unsettable.
  914.    Do this also if `restricted' is already set to 1; maybe the shell was
  915.    started with -r. */
  916. maybe_make_restricted (name)
  917.      char *name;
  918. {
  919.   char *temp;
  920.  
  921.   temp = base_pathname (shell_name);
  922.   if (restricted || (STREQ (temp, "rbash")))
  923.     {
  924.       set_var_read_only ("PATH");
  925.       non_unsettable ("PATH");
  926.       set_var_read_only ("SHELL");
  927.       non_unsettable ("SHELL");
  928.       restricted++;
  929.     }
  930. }
  931. #endif /* RESTRICTED_SHELL */
  932.  
  933. /* Try to execute the contents of FNAME.  If FNAME doesn't exist,
  934.    that is not an error, but other kinds of errors are.  A non-zero
  935.    FORCE_NONINTERACTIVE means to set the value of `interactive' to
  936.    0 so things like job control are disabled; the value is unchanged
  937.    otherwise.  Returns -1 in the case of an error, 0 in the case that
  938.    the file was not found, and 1 if the file was found and executed. */
  939. maybe_execute_file (fname, force_noninteractive)
  940.      char *fname;
  941.      int force_noninteractive;
  942. {
  943.   jmp_buf old_return_catch;
  944.   int return_val, fd, tresult, old_interactive;
  945.   char *filename, *string;
  946.   struct stat file_info;
  947.  
  948.   filename = tilde_expand (fname);
  949.   fd = open (filename, O_RDONLY);
  950.  
  951.   if (fd < 0)
  952.     {
  953. file_error_and_exit:
  954.       if (errno != ENOENT)
  955.     file_error (filename);
  956.       free (filename);
  957.       return ((errno == ENOENT) ? 0 : -1);
  958.     }
  959.  
  960.   if (fstat (fd, &file_info) == -1)
  961.     goto file_error_and_exit;
  962.  
  963.   if (S_ISDIR (file_info.st_mode))
  964.     {
  965.       internal_error ("%s: cannot execute directories", filename);
  966.       free (filename);
  967.       return -1;
  968.     }
  969.  
  970.   string = (char *)xmalloc (1 + (int)file_info.st_size);
  971.   tresult = read (fd, string, file_info.st_size);
  972.  
  973.   {
  974.     int tt = errno;
  975.     close (fd);
  976.     errno = tt;
  977.   }
  978.  
  979.   if (tresult != file_info.st_size)
  980.     {
  981.       free (string);
  982.       goto file_error_and_exit;
  983.     }
  984.   string[file_info.st_size] = '\0';
  985.  
  986.   return_catch_flag++;
  987.   xbcopy ((char *)return_catch, (char *)old_return_catch, sizeof (jmp_buf));
  988.  
  989.   if (force_noninteractive)
  990.     {
  991.       old_interactive = interactive;
  992.       interactive = 0;
  993.     }
  994.  
  995.   return_val = setjmp (return_catch);
  996.  
  997.   /* If `return' was seen outside of a function, but in the script, then
  998.      force parse_and_execute () to clean up. */
  999.   if (return_val)
  1000.     parse_and_execute_cleanup ();
  1001.   else
  1002.     tresult = parse_and_execute (string, filename, -1);
  1003.  
  1004.   if (force_noninteractive)
  1005.     interactive = old_interactive;
  1006.  
  1007.   return_catch_flag--;
  1008.   xbcopy ((char *)old_return_catch, (char *)return_catch, sizeof (jmp_buf));
  1009.  
  1010.   free (filename);
  1011.  
  1012.   return (1);
  1013. }
  1014.  
  1015. #if defined (ONESHOT)
  1016. /* Run one command, given as the argument to the -c option.  Tell
  1017.    parse_and_execute not to fork for a simple command. */
  1018. run_one_command (command)
  1019.      char *command;
  1020. {
  1021.   int code;
  1022.  
  1023.   code = setjmp (top_level);
  1024.  
  1025.   if (code != NOT_JUMPED)
  1026.     {
  1027. #if defined (PROCESS_SUBSTITUTION)
  1028.       unlink_fifo_list ();
  1029. #endif /* PROCESS_SUBSTITUTION */
  1030.       switch (code)
  1031.     {
  1032.       /* Some kind of throw to top_level has occured. */
  1033.     case FORCE_EOF:
  1034.     case EXITPROG:
  1035.     case DISCARD:
  1036.       return 0;
  1037.     default:
  1038.       programming_error ("Bad jump %d", code);
  1039.     }
  1040.     }
  1041.    return (parse_and_execute (savestring (command), "-c", -1));
  1042. }
  1043. #endif /* ONESHOT */
  1044.  
  1045. reader_loop ()
  1046. {
  1047.   int our_indirection_level;
  1048.   COMMAND *current_command = (COMMAND *)NULL;
  1049.  
  1050.   our_indirection_level = ++indirection_level;
  1051.  
  1052.   while (!EOF_Reached)
  1053.     {
  1054.       int code;
  1055.  
  1056.       code = setjmp (top_level);
  1057.  
  1058. #if defined (PROCESS_SUBSTITUTION)
  1059.       unlink_fifo_list ();
  1060. #endif /* PROCESS_SUBSTITUTION */
  1061.  
  1062.       if (interactive_shell)
  1063.     set_signal_handler (SIGINT, sigint_sighandler);
  1064.  
  1065.       if (code != NOT_JUMPED)
  1066.     {
  1067.       indirection_level = our_indirection_level;
  1068.  
  1069.       switch (code)
  1070.         {
  1071.           /* Some kind of throw to top_level has occured. */
  1072.         case FORCE_EOF:
  1073.         case EXITPROG:
  1074.           current_command = (COMMAND *)NULL;
  1075.           EOF_Reached = EOF;
  1076.           goto exec_done;
  1077.  
  1078.         case DISCARD:
  1079.           /* Obstack free command elements, etc. */
  1080.           if (current_command)
  1081.         {
  1082.           dispose_command (current_command);
  1083.           current_command = (COMMAND *)NULL;
  1084.         }
  1085.           break;
  1086.  
  1087.         default:
  1088.           programming_error ("Bad jump %d", code);
  1089.         }
  1090.     }
  1091.  
  1092.       executing = 0;
  1093.       dispose_used_env_vars ();
  1094.  
  1095. #if (defined (Ultrix) && defined (mips)) || !defined (HAVE_ALLOCA)
  1096.       /* Attempt to reclaim memory allocated with alloca (). */
  1097.       (void) alloca (0);
  1098. #endif
  1099.  
  1100.       if (read_command () == 0)
  1101.     {
  1102.       if (global_command)
  1103.         {
  1104.           current_command = global_command;
  1105.  
  1106.           current_command_number++;
  1107.  
  1108.           /* POSIX spec: "-n: The shell reads commands but does
  1109.          not execute them; this can be used to check for shell
  1110.          script syntax errors.  The shell ignores the -n option
  1111.          for interactive shells. " */
  1112.           if (interactive_shell || !read_but_dont_execute)
  1113.         {
  1114.           executing = 1;
  1115.           execute_command (current_command);
  1116.         }
  1117.  
  1118.         exec_done:
  1119.           if (current_command)
  1120.             {
  1121.           dispose_command (current_command);
  1122.           current_command = (COMMAND *)NULL;
  1123.             }
  1124.           QUIT;
  1125.         }
  1126.     }
  1127.       else
  1128.     {
  1129.       /* Parse error, maybe discard rest of stream if not interactive. */
  1130.       if (!interactive)
  1131.         EOF_Reached = EOF;
  1132.     }
  1133.       if (just_one_command)
  1134.     EOF_Reached = EOF;
  1135.     }
  1136.   indirection_level--;
  1137. }
  1138.  
  1139. /* Return a string denoting what our indirection level is. */
  1140. static char indirection_string[100];
  1141.  
  1142. char *
  1143. indirection_level_string ()
  1144. {
  1145.   register int i, j;
  1146.   char *ps4 = get_string_value ("PS4");
  1147.  
  1148.   if (!ps4)
  1149.     ps4 = savestring ("+ ");
  1150.   else
  1151.     ps4 = decode_prompt_string (ps4);
  1152.  
  1153.   for (i = 0; i < indirection_level && i < 99; i++)
  1154.     indirection_string[i] = *ps4;
  1155.  
  1156.   for (j = 1; ps4[j] && i < 99; i++, j++)
  1157.     indirection_string[i] = ps4[j];
  1158.  
  1159.   indirection_string[i] = '\0';
  1160.   free (ps4);
  1161.   return (indirection_string);
  1162. }
  1163.  
  1164. static sighandler 
  1165. alrm_catcher(i)
  1166.      int i;
  1167. {
  1168.   printf ("%ctimed out waiting for input: auto-logout\n", '\07');
  1169.   longjmp (top_level, EXITPROG);
  1170. #if !defined (VOID_SIGHANDLER)
  1171.   return (0);
  1172. #endif /* !VOID_SIGHANDLER */
  1173. }
  1174.  
  1175. parse_command ()
  1176. {
  1177.   int r;
  1178.  
  1179.   need_here_doc = 0;
  1180.   run_pending_traps ();
  1181.  
  1182.   /* Allow the execution of a random command just before the printing
  1183.      of each primary prompt.  If the shell variable PROMPT_COMMAND
  1184.      is set then the value of it is the command to execute. */
  1185.   if (interactive)
  1186.     {
  1187.       char *command_to_execute;
  1188.  
  1189.       command_to_execute = get_string_value ("PROMPT_COMMAND");
  1190.       if (command_to_execute)
  1191.     execute_prompt_command (command_to_execute);
  1192.     }
  1193.  
  1194.   current_command_line_count = 0;
  1195.   r = yyparse ();
  1196.  
  1197.   if (need_here_doc)
  1198.     gather_here_documents ();
  1199.  
  1200.   return (r);
  1201. }
  1202.  
  1203. read_command ()
  1204. {
  1205.   SHELL_VAR *tmout_var = (SHELL_VAR *)NULL;
  1206.   int tmout_len = 0, result;
  1207.   SigHandler *old_alrm = (SigHandler *)NULL;
  1208.  
  1209.   prompt_string_pointer = &ps1_prompt;
  1210.   global_command = (COMMAND *)NULL;
  1211.  
  1212.   /* Only do timeouts if interactive. */
  1213.   if (interactive)
  1214.     {
  1215.       tmout_var = find_variable ("TMOUT");
  1216.  
  1217.       if (tmout_var && tmout_var->value)
  1218.     {
  1219.       tmout_len = atoi (tmout_var->value);
  1220.       if (tmout_len > 0)
  1221.         {
  1222.           old_alrm = set_signal_handler (SIGALRM, alrm_catcher);
  1223.           alarm (tmout_len);
  1224.         }
  1225.     }
  1226.     }
  1227.  
  1228.   QUIT;
  1229.  
  1230.   current_command_line_count = 0;
  1231.   result = parse_command ();
  1232.  
  1233.   if (interactive && tmout_var && (tmout_len > 0))
  1234.     {
  1235.       alarm(0);
  1236.       set_signal_handler (SIGALRM, old_alrm);
  1237.     }
  1238.   return (result);
  1239. }
  1240.  
  1241. /* Cause STREAM to buffer lines as opposed to characters or blocks. */
  1242. static void
  1243. line_buffer_stream (stream)
  1244.      FILE *stream;
  1245. {
  1246.   /* If your machine doesn't have either of setlinebuf or setvbuf,
  1247.      you can just comment out the buffering commands, and the shell
  1248.      will still work.  It will take more cycles, though. */
  1249. #if defined (HAVE_SETLINEBUF)
  1250.   setlinebuf (stream);
  1251. #else
  1252. #  if defined (_IOLBF)
  1253. #    if defined (REVERSED_SETVBUF_ARGS)
  1254.   setvbuf (stream, _IOLBF, (char *)NULL, BUFSIZ);
  1255. #    else /* !REVERSED_SETVBUF_ARGS */
  1256.   setvbuf (stream, (char *)NULL, _IOLBF, BUFSIZ);
  1257. #    endif /* !REVERSED_SETVBUF_ARGS */
  1258. #  endif /* _IOLBF */
  1259. #endif /* !HAVE_SETLINEBUF */
  1260. }
  1261.  
  1262. /* Do whatever is necessary to initialize the shell.
  1263.    Put new initializations in here. */
  1264. static void
  1265. shell_initialize ()
  1266. {
  1267.   /* Line buffer output for stderr and stdout. */
  1268.   line_buffer_stream (stderr);
  1269.   line_buffer_stream (stdout);
  1270.  
  1271.   /* Sort the array of shell builtins so that the binary search in
  1272.      find_shell_builtin () works correctly. */
  1273.   initialize_shell_builtins ();
  1274.  
  1275.   /* Initialize the trap signal handlers before installing our own
  1276.      signal handlers.  traps.c:restore_original_signals () is responsible
  1277.      for restoring the original default signal handlers.  That function
  1278.      is called when we make a new child. */
  1279.   initialize_traps ();
  1280.   initialize_signals ();
  1281.  
  1282.   /* Initialize current_user.name and current_host_name. */
  1283.   {
  1284.     struct passwd *entry = getpwuid (current_user.uid);
  1285.     char hostname[256];
  1286.  
  1287.     if (gethostname (hostname, 255) < 0)
  1288.       current_host_name = "??host??";
  1289.     else
  1290.       current_host_name = savestring (hostname);
  1291.  
  1292.     if (entry)
  1293.       {
  1294.     current_user.user_name = savestring (entry->pw_name);
  1295.     if (entry->pw_shell && entry->pw_shell[0])
  1296.       current_user.shell = savestring (entry->pw_shell);
  1297.     else
  1298.       current_user.shell = savestring ("/bin/sh");
  1299.     current_user.home_dir = savestring (entry->pw_dir);
  1300.       }
  1301.     else
  1302.       {
  1303.     current_user.user_name = savestring ("I have no name!");
  1304.     current_user.shell = savestring ("/bin/sh");
  1305.     current_user.home_dir = savestring ("/");
  1306.       }
  1307.  
  1308.     endpwent ();
  1309.   }
  1310.  
  1311.   /* Initialize our interface to the tilde expander. */
  1312.   tilde_initialize ();
  1313.  
  1314.   /* Initialize internal and environment variables. */
  1315.   initialize_shell_variables (shell_environment);
  1316.  
  1317.   /* Initialize filename hash tables. */
  1318.   initialize_filename_hashing ();
  1319.  
  1320.   /* Initialize the data structures for storing and running jobs. */
  1321.   initialize_jobs ();
  1322.  
  1323.   /* Initialize input streams to null. */
  1324.   initialize_bash_input ();
  1325. }
  1326.  
  1327. /* Function called by main () when it appears that the shell has already
  1328.    had some initialization performed.  This is supposed to reset the world
  1329.    back to a pristine state, as if we had been exec'ed. */
  1330. static void
  1331. shell_reinitialize ()
  1332. {
  1333.   /* The default shell prompts. */
  1334.   primary_prompt = PPROMPT;
  1335.   secondary_prompt = SPROMPT;
  1336.  
  1337.   /* Things that get 1. */
  1338.   current_command_number = 1;
  1339.  
  1340.   /* We have decided that the ~/.bashrc file should not be executed
  1341.      for the invocation of each shell script.  If the variable $ENV
  1342.      (or $BASH_ENV) is set, its value is used as the name of a file
  1343.      to source. */
  1344.   no_rc = no_profile = 1;
  1345.  
  1346.   /* Things that get 0. */
  1347.   login_shell = make_login_shell = interactive = executing = 0;
  1348.   debugging = do_version = line_number = last_command_exit_value = 0;
  1349.   forced_interactive = interactive_shell = subshell_environment = 0;
  1350.  
  1351. #if defined (HISTORY)
  1352.   remember_on_history = history_expansion = 0;
  1353. #endif /* HISTORY */
  1354.  
  1355. #if defined (RESTRICTED_SHELL)
  1356.   restricted = 0;
  1357. #endif /* RESTRICTED_SHELL */
  1358.  
  1359.   /* Ensure that the default startup file is used.  (Except that we don't
  1360.      execute this file for reinitialized shells). */
  1361.   bashrc_file = "~/.bashrc";
  1362.  
  1363.   /* Delete all variables and functions.  They will be reinitialized when
  1364.      the environment is parsed. */
  1365.  
  1366.   delete_all_variables (shell_variables);
  1367.   delete_all_variables (shell_functions);
  1368.  
  1369.   /* Pretend the PATH variable has changed. */
  1370.   sv_path ("PATH");
  1371. }
  1372.  
  1373. static void
  1374. initialize_signals ()
  1375. {
  1376.   initialize_terminating_signals ();
  1377.   initialize_job_signals ();
  1378. #if defined (INITIALIZE_SIGLIST)
  1379.   initialize_siglist ();
  1380. #endif
  1381. }
  1382.  
  1383. /* A structure describing a signal that terminates the shell if not
  1384.    caught.  The orig_handler member is present so children can reset
  1385.    these signals back to their original handlers. */
  1386. struct termsig {
  1387.      int signum;
  1388.      SigHandler *orig_handler;
  1389. };
  1390.  
  1391. #define NULL_HANDLER (SigHandler *)SIG_DFL
  1392.  
  1393. /* The list of signals that would terminate the shell if not caught.
  1394.    We catch them, but just so that we can write the history file,
  1395.    and so forth. */
  1396. static struct termsig terminating_signals[] = {
  1397. #ifdef SIGHUP
  1398.   SIGHUP, NULL_HANDLER,
  1399. #endif
  1400.  
  1401. #ifdef SIGINT
  1402.   SIGINT, NULL_HANDLER,
  1403. #endif
  1404.  
  1405. #ifdef SIGILL
  1406.   SIGILL, NULL_HANDLER,
  1407. #endif
  1408.  
  1409. #ifdef SIGTRAP
  1410.   SIGTRAP, NULL_HANDLER,
  1411. #endif
  1412.  
  1413. #ifdef SIGIOT
  1414.   SIGIOT, NULL_HANDLER,
  1415. #endif
  1416.  
  1417. #ifdef SIGDANGER
  1418.   SIGDANGER, NULL_HANDLER,
  1419. #endif
  1420.  
  1421. #ifdef SIGEMT
  1422.   SIGEMT, NULL_HANDLER,
  1423. #endif
  1424.  
  1425. #ifdef SIGFPE
  1426.   SIGFPE, NULL_HANDLER,
  1427. #endif
  1428.  
  1429. #ifdef SIGBUS
  1430.   SIGBUS, NULL_HANDLER,
  1431. #endif
  1432.  
  1433. #ifdef SIGSEGV
  1434.   SIGSEGV, NULL_HANDLER,
  1435. #endif
  1436.  
  1437. #ifdef SIGSYS
  1438.   SIGSYS, NULL_HANDLER,
  1439. #endif
  1440.  
  1441. #ifdef SIGPIPE
  1442.   SIGPIPE, NULL_HANDLER,
  1443. #endif
  1444.  
  1445. #ifdef SIGALRM
  1446.   SIGALRM, NULL_HANDLER,
  1447. #endif
  1448.  
  1449. #ifdef SIGTERM
  1450.   SIGTERM, NULL_HANDLER,
  1451. #endif
  1452.  
  1453. #ifdef SIGXCPU
  1454.   SIGXCPU, NULL_HANDLER,
  1455. #endif
  1456.  
  1457. #ifdef SIGXFSZ
  1458.   SIGXFSZ, NULL_HANDLER,
  1459. #endif
  1460.  
  1461. #ifdef SIGVTALRM
  1462.   SIGVTALRM, NULL_HANDLER,
  1463. #endif
  1464.  
  1465. #ifdef SIGPROF
  1466.   SIGPROF, NULL_HANDLER,
  1467. #endif
  1468.  
  1469. #ifdef SIGLOST
  1470.   SIGLOST, NULL_HANDLER,
  1471. #endif
  1472.  
  1473. #ifdef SIGUSR1
  1474.   SIGUSR1, NULL_HANDLER,
  1475. #endif
  1476.  
  1477. #ifdef SIGUSR2
  1478.   SIGUSR2, NULL_HANDLER,
  1479. #endif
  1480. };
  1481.  
  1482. #define TERMSIGS_LENGTH (sizeof (terminating_signals) / sizeof (struct termsig))
  1483.  
  1484. #define XSIG(x) (terminating_signals[x].signum)
  1485. #define XHANDLER(x) (terminating_signals[x].orig_handler)
  1486.  
  1487. /* This function belongs here? */
  1488. sighandler
  1489. termination_unwind_protect (sig)
  1490.      int sig;
  1491. {
  1492.   if (sig == SIGINT && signal_is_trapped (SIGINT))
  1493.     run_interrupt_trap ();
  1494.  
  1495. #if defined (HISTORY)
  1496.   if (interactive && remember_on_history)
  1497.     maybe_save_shell_history ();
  1498. #endif /* HISTORY */
  1499.  
  1500. #if defined (JOB_CONTROL)
  1501.   if (interactive && login_shell && sig == SIGHUP)
  1502.     hangup_all_jobs ();
  1503.   end_job_control ();
  1504. #endif /* JOB_CONTROL */
  1505.  
  1506. #if defined (PROCESS_SUBSTITUTION)
  1507.   unlink_fifo_list ();
  1508. #endif /* PROCESS_SUBSTITUTION */
  1509.  
  1510.   run_exit_trap ();
  1511.   signal (sig, SIG_DFL);
  1512.   kill (getpid (), sig);
  1513.  
  1514. #if !defined (VOID_SIGHANDLER)
  1515.   return (0);
  1516. #endif /* VOID_SIGHANDLER */
  1517. }
  1518.  
  1519. /* Initialize signals that will terminate the shell to do some
  1520.    unwind protection. */
  1521. static void
  1522. initialize_terminating_signals ()
  1523. {
  1524.   register int i;
  1525.  
  1526.   /* The following code is to avoid an expensive call to
  1527.      set_signal_handler () for each terminating_signals.  Fortunately,
  1528.      this is possible in Posix.  Unfortunately, we have to call signal ()
  1529.      on non-Posix systems for each signal in terminating_signals. */
  1530. #if defined (_POSIX_VERSION)
  1531.   struct sigaction act, oact;
  1532.  
  1533.   act.sa_handler = termination_unwind_protect;
  1534.   act.sa_flags = 0;
  1535.   sigemptyset (&act.sa_mask);
  1536.   sigemptyset (&oact.sa_mask);
  1537.   for (i = 0; i < TERMSIGS_LENGTH; i++)
  1538.     sigaddset (&act.sa_mask, XSIG (i));
  1539.   for (i = 0; i < TERMSIGS_LENGTH; i++)
  1540.     {
  1541.       sigaction (XSIG (i), &act, &oact);
  1542.       terminating_signals[i].orig_handler = oact.sa_handler;
  1543.       /* Don't do anything with signals that are ignored at shell entry
  1544.      if the shell is not interactive. */
  1545.       if (!interactive_shell && oact.sa_handler == SIG_IGN)
  1546.         {
  1547.       sigaction (XSIG (i), &oact, &act);
  1548.       set_signal_ignored (XSIG (i));
  1549.         }
  1550.     }
  1551.  
  1552. #else /* !_POSIX_VERSION */
  1553.  
  1554.   for (i = 0; i < TERMSIGS_LENGTH; i++)
  1555.     {
  1556.       terminating_signals[i].orig_handler =
  1557.     signal (XSIG (i), termination_unwind_protect);
  1558.       /* Don't do anything with signals that are ignored at shell entry
  1559.      if the shell is not interactive. */
  1560.       if (!interactive_shell && terminating_signals[i].orig_handler == SIG_IGN)
  1561.     {
  1562.           signal (XSIG (i), SIG_IGN);
  1563.           set_signal_ignored (XSIG (i));
  1564.     }
  1565.     }
  1566.  
  1567. #endif /* !_POSIX_VERSION */
  1568.  
  1569. #if defined (JOB_CONTROL) || defined (_POSIX_VERSION)
  1570.   /* All shells use the signal mask they inherit, and pass it along
  1571.      to child processes.  Children will never block SIGCHLD, though. */
  1572.   sigemptyset (&top_level_mask);
  1573.   sigprocmask (SIG_BLOCK, (sigset_t *)NULL, &top_level_mask);
  1574.   sigdelset (&top_level_mask, SIGCHLD);
  1575. #endif /* JOB_CONTROL || _POSIX_VERSION */
  1576.  
  1577.   /* And, some signals that are specifically ignored by the shell. */
  1578.   signal (SIGQUIT, SIG_IGN);
  1579.  
  1580.   if (interactive)
  1581.     {
  1582.       set_signal_handler (SIGINT, sigint_sighandler);
  1583.       signal (SIGTERM, SIG_IGN);
  1584.     }
  1585. }
  1586.  
  1587. void
  1588. reset_terminating_signals ()
  1589. {
  1590.   register int i;
  1591.  
  1592. #if defined (_POSIX_VERSION)
  1593.   struct sigaction act;
  1594.  
  1595.   act.sa_flags = 0;
  1596.   sigemptyset (&act.sa_mask);
  1597.   for (i = 0; i < TERMSIGS_LENGTH; i++)
  1598.     {
  1599.       /* Skip a signal if it's trapped or handled specially, because the
  1600.      trap code will restore the correct value. */
  1601.       if (signal_is_trapped (XSIG (i)) || signal_is_special (XSIG (i)))
  1602.     continue;
  1603.  
  1604.       act.sa_handler = XHANDLER (i);
  1605.       sigaction (XSIG (i), &act, (struct sigaction *) NULL);
  1606.     }
  1607. #else
  1608.   for (i = 0; i < TERMSIGS_LENGTH; i++)
  1609.     {
  1610.       if (signal_is_trapped (XSIG (i)) || signal_is_special (XSIG (i)))
  1611.     continue;
  1612.  
  1613.       signal (XSIG (i), XHANDLER (i));
  1614.     }
  1615. #endif
  1616. }
  1617. #undef XSIG
  1618. #undef XHANDLER
  1619.  
  1620. /* What to do when we've been interrupted, and it is safe to handle it. */
  1621. void
  1622. throw_to_top_level ()
  1623. {
  1624.   int print_newline = 0;
  1625.  
  1626.   if (interrupt_state)
  1627.     {
  1628.       print_newline = 1;
  1629.       interrupt_state--;
  1630.     }
  1631.  
  1632.   if (interrupt_state)
  1633.     return;
  1634.  
  1635.   last_command_exit_value |= 128;
  1636.  
  1637.   /* Run any traps set on SIGINT. */
  1638.   run_interrupt_trap ();
  1639.  
  1640.   /* Cleanup string parser environment. */
  1641.   while (parse_and_execute_level)
  1642.     parse_and_execute_cleanup ();
  1643.  
  1644. #if defined (JOB_CONTROL)
  1645.   give_terminal_to (shell_pgrp);
  1646. #endif /* JOB_CONTROL */
  1647.  
  1648. #if defined (JOB_CONTROL) || defined (_POSIX_VERSION)
  1649.   sigprocmask (SIG_SETMASK, &top_level_mask, (sigset_t *)NULL);
  1650. #endif
  1651.  
  1652.   reset_parser ();
  1653.  
  1654. #if defined (READLINE)
  1655.   if (interactive)
  1656.     bashline_reinitialize ();
  1657. #endif /* READLINE */
  1658.  
  1659. #if defined (PROCESS_SUBSTITUTION)
  1660.   unlink_fifo_list ();
  1661. #endif /* PROCESS_SUBSTITUTION */
  1662.  
  1663.   run_unwind_protects ();
  1664.   loop_level = continuing = breaking = 0;
  1665.   return_catch_flag = 0;
  1666.  
  1667.   if (interactive && print_newline)
  1668.     {
  1669.       fflush (stdout);
  1670.       fprintf (stderr, "\n");
  1671.       fflush (stderr);
  1672.     }
  1673.  
  1674.   /* An interrupted `wait' command in a script does not exit the script. */
  1675.   if (interactive || (interactive_shell && !shell_initialized) ||
  1676.       (print_newline && signal_is_trapped (SIGINT)))
  1677.     longjmp (top_level, DISCARD);
  1678.   else
  1679.     longjmp (top_level, EXITPROG);
  1680. }
  1681.  
  1682. /* When non-zero, we throw_to_top_level (). */
  1683. int interrupt_immediately = 0;
  1684.  
  1685. /* What we really do when SIGINT occurs. */
  1686. sighandler
  1687. sigint_sighandler (sig)
  1688.      int sig;
  1689. {
  1690. #if defined (USG) && !defined (_POSIX_VERSION)
  1691.   signal (sig, sigint_sighandler);
  1692. #endif
  1693.  
  1694.   /* interrupt_state needs to be set for the stack of interrupts to work
  1695.      right.  Should it be set unconditionally? */
  1696.   if (!interrupt_state)
  1697.     interrupt_state++;
  1698.  
  1699.   if (interrupt_immediately)
  1700.     {
  1701.       interrupt_immediately = 0;
  1702.       throw_to_top_level ();
  1703.     }
  1704. #if !defined (VOID_SIGHANDLER)
  1705.   return (0);
  1706. #endif /* VOID_SIGHANDLER */
  1707. }
  1708.  
  1709. /* Give version information about this shell. */
  1710. char *
  1711. shell_version_string ()
  1712. {
  1713.   static char tt[16] = { '\0' };
  1714.  
  1715.   if (!tt[0])
  1716.     sprintf (tt, "%s.%d(%d)", dist_version, patch_level, build_version);
  1717.   return tt;
  1718. }
  1719.  
  1720. void
  1721. show_shell_version ()
  1722. {
  1723.   printf ("GNU %s, version %s\n", base_pathname (shell_name),
  1724.     shell_version_string ());
  1725. }
  1726.  
  1727. #if !defined (USG) && defined (ENOTSOCK)
  1728. #  if !defined (HAVE_SOCKETS)
  1729. #    define HAVE_SOCKETS
  1730. #  endif
  1731. #endif
  1732.  
  1733. #if defined (HAVE_SOCKETS)
  1734. #include <sys/socket.h>
  1735. #endif
  1736.  
  1737. /* Is FD a socket or network connection? */
  1738. static int
  1739. isnetconn (fd)
  1740.      int fd;
  1741. {
  1742. #if defined (USGr4) || defined (USGr4_2)
  1743.   /* Sockets on SVR4 and SVR4.2 are character special (streams) devices. */
  1744.   struct stat sb;
  1745.  
  1746.   if (fstat (fd, &sb) < 0)
  1747.     return (0);
  1748.   return (S_ISCHR (sb.st_mode));
  1749. #else /* !USGr4 && !USGr4_2 */
  1750. #  if defined (HAVE_SOCKETS)
  1751.   int rv, l;
  1752.   struct sockaddr sa;
  1753.  
  1754.   l = sizeof(sa);
  1755.   rv = getpeername(0, &sa, &l);
  1756.   return ((rv < 0 && errno == ENOTSOCK) ? 0 : 1);
  1757. #  else /* !HAVE_SOCKETS */
  1758. #    if defined (S_ISSOCK)
  1759.   struct stat sb;
  1760.  
  1761.   if (fstat (fd, &sb) < 0)
  1762.     return (0);
  1763.   return (S_ISSOCK (sb.st_mode));
  1764. #    else /* !S_ISSOCK */
  1765.   return (0);
  1766. #    endif /* !S_ISSOCK */
  1767. #  endif /* !HAVE_SOCKETS */
  1768. #endif /* !USGr4 && !USGr4_2 */
  1769. }
  1770.